#include "pch.hpp"
#include "System.hpp"




ResourceSystem::ResourceSystem(const VideoDevicePtr& videoDevice, const AudioDevicePtr& audioDevice)
	: m_videoDevice(videoDevice)
	, m_audioDevice(audioDevice)
{}
///////////////////////////////////////////////////////////////////////////////////////////////////




QString ResourceSystem::name() const
{
	return "Resource System";
}
///////////////////////////////////////////////////////////////////////////////////////////////////

void ResourceSystem::update()
{
	// TODO: Check for unused resources
	//       USE LRU algorithm to remove unused resources
}
///////////////////////////////////////////////////////////////////////////////////////////////////




EffectPtr ResourceSystem::createEffect(QString name, bool* created)
{
	EffectMap::const_iterator i = m_effects.find(name);
	EffectPtr tmp;

	if(i == m_effects.end())
	{
		tmp = m_videoDevice->createEffect(name);
		m_effects.insert(std::make_pair(name, tmp));
		if(created) *created = true;
	}
	else
	{
		tmp = i->second;
		if(created) *created = false;
	}

	return tmp;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

TexturePtr ResourceSystem::createTexture(QString fname, bool* created)
{
	TextureMap::const_iterator i = m_textures.find(fname);
	TexturePtr tmp;

	if(i == m_textures.end())
	{
		if(m_textureFN)
			tmp = m_textureFN(fname);
		else
			tmp = m_videoDevice->createTexture(fname);

		m_textures.insert(std::make_pair(fname, tmp));
		if(created) *created = true;
	}
	else
	{
		tmp = i->second;
		if(created) *created = false;
	}

	return tmp;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

void ResourceSystem::clearCache()
{
	// If we're the only one still holding a reference to a texture or effect,
	// then it qualifies for being trashed.

	for(EffectMap::iterator i = m_effects.begin(); i != m_effects.end();)
	{
		if(i->second.refCount() == 1)
			i = m_effects.erase(i);
		else
			++i;
	}

	for(TextureMap::iterator i = m_textures.begin(); i != m_textures.end();)
	{
		if(i->second.refCount() == 1)
			i = m_textures.erase(i);
		else
			++i;
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////




void ResourceSystem::setFunctor(TextureLoad fn)
{
	m_textureFN = fn;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
